Imports System.Runtime.InteropServices

Namespace Protocol.Functions

    Public Module mFunctions

        Public Function ArrayToStruct(ByRef buffer() As Byte, ByVal t As Type, Optional ByVal offset As Int32 = 0) As Object

            ' pin variable and create
            ' GC handle instance
            Dim gh As GCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned)
            ' get address of variable
            Dim AddrOfArray As IntPtr = gh.AddrOfPinnedObject()
            Return Marshal.PtrToStructure(New IntPtr(AddrOfArray.ToInt32 + offset), t)
            ' free the handle and unpin variable
            gh.Free()

        End Function

        Public Function StructToArray(ByRef struct As Object, ByVal t As Type) As Byte()

            Dim ptr As IntPtr

            ptr = Marshal.AllocHGlobal(Marshal.SizeOf(t))
            Marshal.StructureToPtr(struct, ptr, False)

            Dim bytes(Marshal.SizeOf(t) - 1) As Byte

            Marshal.Copy(ptr, bytes, 0, Marshal.SizeOf(t))

            Return bytes

        End Function

        'Public Function SessionIDToStr(bSessionID() As Byte) As String

        '    Dim ret As String = ""

        '    For i As Integer = 0 To 3
        '        ret &= Chr(bSessionID(i))
        '    Next

        '    Return ret

        'End Function

        Public Function RandNum(min As Long, max As Long) As Long

            Randomize()
            Return CLng(Math.Floor((max - min + 1) * Rnd())) + min

        End Function

    End Module

End Namespace